package cs4295asg2.stockfinder;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class StockDetails extends Activity {
	public final static String STOCK_NO = "cs4295asg2.stockfinder.input";
	public final static String CURR_PRICE = "cs4295asg2.stockfinder.currentPrice";
	StockDetails selfRef;
	private BufferedReader reader = null;
	
	
	public static boolean isNumeric(String str) {  
		try {  
			int d = Integer.parseInt(str);  
		}  
		catch(NumberFormatException nfe) {  
			return false;  
		}  
		return true;  
	}
	
	public static String validate(String str) {
		try {
			if (isNumeric(str))
				return str + ".HK";
			return URLEncoder.encode(str, "UTF-8");
		} catch (UnsupportedEncodingException ex) {
			Log.i("URLValidat", "URLEncoder.encode Unsupported Encoding Exception ");
			ex.printStackTrace();
		}
		return "ErrorInput";
	}
	
	
	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        selfRef = this;
        setContentView(R.layout.stock_details);
        Intent i = getIntent();
        String inputStockSymbol = i.getStringExtra(MainActivity.STOCK_NO).toString().toUpperCase();
        String strURL;
        Log.i("Stock No", inputStockSymbol);
        String validatedStockSymbol = validate(inputStockSymbol);
        strURL = "http://download.finance.yahoo.com/d/quotes.csv?s="+ validatedStockSymbol +"&f=nsl1opc1";
        Log.i("strURL: ", strURL);
        
        final TextView stockName = (TextView)findViewById(R.id.stockName);
        final TextView stockSymbol = (TextView)findViewById(R.id.stockSym);
        final TextView stockCurrPrice = (TextView)findViewById(R.id.currPrice);
        final TextView stockOpen = (TextView)findViewById(R.id.open);
        final TextView stockPrevClose = (TextView)findViewById(R.id.prevClose);
        final TextView stockChange = (TextView)findViewById(R.id.change);
        //make connection --------------------
        class HostConnection extends AsyncTask<String, Void, InputStream> {
            private Exception ex;

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }

            protected InputStream doInBackground(String... urls) {
                try {
                    // defaultHttpClient
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    HttpGet httpGet = new HttpGet(urls[0]);
                    HttpContext localContext = new BasicHttpContext();
                    HttpResponse httpResponse = httpClient.execute(httpGet, localContext);
                    HttpEntity httpEntity = httpResponse.getEntity();
                    return httpEntity.getContent();
                } catch (Exception e) {
                    this.ex = e;
                    Log.i("HostConnection", "Error in DefaultHttpClient");
                    return null;
                } 
            }
            @Override
            protected void onPostExecute(InputStream is) {
                super.onPostExecute(is);
                reader = new BufferedReader(new InputStreamReader(is));
                try {
                	String line;
                	while ((line = reader.readLine()) != null){
                		String[] RowData = line.split(",");
                		if(RowData.length >=6){
                			String name = RowData[0];
	                		String symbol = RowData[1];
	                		String currPrice = RowData[2];
	                		String open = RowData[3];
	                		String prevClose = RowData[4];
	                		String change = RowData[5];
	
	                		stockName.setText(name);
	                		stockSymbol.setText(symbol);
	                		stockCurrPrice.setText(currPrice);
	                		stockOpen.setText(open);
	                		stockPrevClose.setText(prevClose);
	                		stockChange.setText(change);
                		}
                		else
                			stockSymbol.setText("Missing Symbols List.");
                	}
                } catch (IOException ex) {
                	Log.i("HostConnection", "Error in onPostExecute's reader.readLine(IOException)");
                	ex.printStackTrace();
                } finally {
                	try {
                		is.close();
                	} catch (IOException e) {
                		Log.i("HostConnection", "Error in close(IOException)");
                		e.printStackTrace();
                	}
                }
            }
        }
        //end make connection --------------------
        new HostConnection().execute(strURL);
        
        
        //Add to Favorite List Button
        Button add_fav_button = (Button) this.findViewById(R.id.add_to_fav);
        final String temp = inputStockSymbol;
        add_fav_button.setOnClickListener(new OnClickListener() {
        	public void onClick(View v) {
        		Intent i = new Intent(selfRef, FavouriteStocks.class);
        		i.putExtra(STOCK_NO, temp);
        		i.putExtra(CURR_PRICE, stockCurrPrice.getText().toString());
        		startActivity(i);
        	}
        });
        //end Add to Favorite List Button
    }

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.stock_details, menu);
		return true;
	}

}